package com.powernode.api;

import com.powernode.domain.CreateWxPaymentForm;
import com.powernode.domain.WxPrepayVo;
import com.powernode.model.Result;
import com.powernode.service.IWxPayService;
import com.powernode.service.PaymentService;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("/p")

@CrossOrigin("*")
public class WxPayApiController {
    @Autowired
    private IWxPayService wxPayService;

    @Autowired
    private PaymentService paymentService;

    @Operation(summary = "支付状态查询")
    @PostMapping("/queryPayStatus/{orderNumber}")
    public Result queryPayStatus(@PathVariable("orderNumber") String orderNumber) {
        //根据订单编号调用微服务接口，查询支付相关状态信息
        Transaction transaction = wxPayService.queryPayStatus(orderNumber);
        //根据微服务返回结果，判断支付是否成功
        if (transaction != null && transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
            paymentService.updatePaymentStatus(transaction);
            return Result.success(true);
        }
        return Result.fail(404,"支付失败");
    }

    @Operation(summary = "微信支付异步通知接口")
    @PostMapping("/wxPay/notify")
    public Map<String, Object> notify(HttpServletRequest request) {
        try {
            wxPayService.wxnotify(request);

            // 返回成功
            Map<String, Object> result = new HashMap<>();
            result.put("code", "SUCCESS");
            result.put("message", "成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 返回失败
        Map<String, Object> result = new HashMap<>();
        result.put("code", "FAIL");
        result.put("message", "失败");
        return result;
    }

    @Operation(summary = "微信下单")
    @PostMapping("/order/pay")
    public Result createWxPayment(@RequestBody CreateWxPaymentForm createWxPaymentForm) {
        //调用微信支付接口，生成微信支付二维码
        WxPrepayVo wxPrepayVo = wxPayService.createWxPayment(createWxPaymentForm);
        //返回微信支付二维码
        return Result.success(wxPrepayVo);
    }
}
